<template>
  <div class="fulltable">
    <div class="full">
      <div class="search">
        <el-input v-model="searchName" placeholder="输入申请人" @input="filterData" clearable style="margin-right: 10px;width:200px"></el-input>
        <el-select v-model="selectedStatus" placeholder="筛选状态" clearable style="margin-right: 10px;width:200px">
          <el-option v-for="status in stateSearchOptions" :key="status.value" :label="status.label" :value="status.value"></el-option>
        </el-select>
        <el-select v-model="selectedType" placeholder="筛选类型" clearable style="margin-right: 10px;width:200px">
          <el-option v-for="type in typeOptions" :key="type" :label="type" :value="type"></el-option>
        </el-select>
      </div>
      <el-table
        :data="filteredVacationData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" 
        :height="tableHeight"
        border
        style="width: 100%;border-radius: 10px;">
        <el-table-column
          prop="state"
          label="状态"
          width="100">
        </el-table-column>
        <el-table-column
          prop="name"
          label="申请人"
          width="130"
          >
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          width="100">
        </el-table-column>
        <el-table-column
          prop="starttime"
          label="开始时间"
          width="200">
        </el-table-column>
        <el-table-column
          prop="deadline"
          label="结束时间"
          width="180">
        </el-table-column>
        <el-table-column
          prop="time"
          label="申请时间"
          width="200">
        </el-table-column>
        <el-table-column
          prop="examine"
          label="审核状态"
          width="100"
          >
        </el-table-column>
        <el-table-column label="操作" >  
          <template slot-scope="scope">  
            <el-button type="primary" size="small" @click="viewItem(scope.row)">详情</el-button>  
            <el-button
              v-if="canEditItem(scope.row)"
              type="warning"
              size="small"
              @click="editItem(scope.row)">编辑</el-button> 
          </template>  
        </el-table-column>  
      </el-table>
      <div class="paging">
        <el-pagination  
          @size-change="handleSizeChange"  
          @current-change="handleCurrentChange"  
          :current-page="currentPage"  
          :page-sizes="[5,10, 20, 40, 60]"  
          :page-size="pageSize"  
          :pager-count="4"
          layout="total, sizes, prev, pager, next, jumper"  
          :total="filteredVacationData.length">  
        </el-pagination> 
      </div>
    </div>
    <el-dialog title="假期申请详情" :visible.sync="showDetailModal" width="50%">  
  <el-form :model="detailItem" label-width="80px">  
    <el-form-item label="申请人">  
      <el-input v-model="detailItem.name" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="状态">  
      <el-input v-model="detailItem.state" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="类型">  
      <el-input v-model="detailItem.type" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="开始时间">  
      <el-input v-model="detailItem.starttime" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="结束时间">  
      <el-input v-model="detailItem.deadline" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="原因">  
      <el-input type="textarea" v-model="detailItem.reason" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="申请时间">  
      <el-input v-model="detailItem.time" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="审核状态">  
      <el-input v-model="detailItem.examine" disabled></el-input>  
    </el-form-item>  
    <el-form-item label="审核人">  
      <el-input v-model="detailItem.reviewer" disabled></el-input>  
    </el-form-item>  
        <el-form-item label="审核原因">  
      <el-input v-model="detailItem.exreason" disabled></el-input>  
    </el-form-item>  
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="showDetailModal = false">取 消</el-button>  
  </span>  
</el-dialog>

<el-dialog title="编辑假期申请" :visible.sync="showEditModal" width="30%" :close-on-click-modal="false">
  <div style="color: red; margin-bottom: 10px;">非通过的信息，编辑保存后默认改为待审核状态</div>
  <el-form :model="editVacation" label-width="80px" ref="editVacationForm">
    <el-form-item label="状态" prop="state" :rules="[{ required: true, message: '状态不能为空' }]">
      <el-select v-model="editVacation.state" placeholder="请选择状态">
        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '类型不能为空' }]">
      <el-select v-model="editVacation.type" placeholder="请选择类型">
        <el-option v-for="type in typeOptions" :key="type" :label="type" :value="type"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="开始时间" prop="starttime" :rules="[{ required: true, message: '开始时间不能为空' }]">
      <el-date-picker v-model="editVacation.starttime" type="datetime" placeholder="选择开始时间"></el-date-picker>
    </el-form-item>
    <el-form-item label="结束时间" prop="deadline" :rules="[{ required: true, message: '结束时间不能为空' }]">
      <el-date-picker v-model="editVacation.deadline" type="datetime" placeholder="选择结束时间"></el-date-picker>
    </el-form-item>
    <el-form-item label="原因" prop="reason" :rules="[{ required: true, message: '原因不能为空' }]">
      <el-input v-model="editVacation.reason" type="textarea"></el-input>
    </el-form-item>
    <el-form-item label="审核人" prop="reviewer" >
      <el-input v-model="fatherName" style="width:400px" disabled></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="closeEditModal">取 消</el-button>
    <el-button type="primary" @click="updateVacationById">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import {getApproved,getVacationDetailById,updateVacation} from '@/api/vacation';
import {addLog} from '@/api/log';
import {getFather} from '@/api/user';
import {jwtDecode } from 'jwt-decode';
export default {
  data(){
     return {  
      logItem:{
              mn:'',
              opn:'',
              res:''
      },
      showEditModal: false, // 控制编辑弹窗的显示
    editVacation: { // 用于编辑的假期信息
      name: '',
      type: '',
      starttime: '',
      deadline: '',
      reason: '',
      state: '',
      reviewer: null,
      examine: '0'
    },
    stateOptions: [  
          { label: '正常', value: 3 },  
          { label: '重要', value: 2 },  
          { label: '紧急', value: 1 }  
        ],
    fatherName:'',
    fatherId:'',
    userId:'',
    isSuperman:false,
        vacationData:[],
        currentPage: 1,  
        pageSize: 5  ,
        tableHeight: 350,  
        maxTableHeight: 700, // 最大高度 600px  
        minTableHeight: 350,
        selectedStatus: '',
        selectedType: '',
        searchName: '',
        detailItem: {}, // 存储选中的假期申请详细信息  
        stateSearchOptions: [  
          { label: '正常', value: '正常' },  
          { label: '重要', value: '重要' },  
          { label: '紧急', value: '紧急' }  
        ],
        showDetailModal:false,
        typeOptions: ['年假', '病假', '事假', '婚假', '产假及哺乳假', '陪产假', '丧假', '调休'],
    }
  },
  computed: {
    filteredVacationData() {
      return this.vacationData.filter(item => {
        const matchesName = item.name.toLowerCase().includes(this.searchName.toLowerCase());
        const matchesStatus = this.selectedStatus ? item.state === this.selectedStatus : true;
        const matchesType = this.selectedType ? item.type === this.selectedType : true;
        return matchesName && matchesStatus && matchesType;
      });
    },
  },
  created(){
    getApproved().then(response=>{
      this.vacationData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight  
    })
    getFather().then(response=>{
      this.fatherName = response.data.realname;
      this.fatherId = response.data.id;
    })
    this.userId = this.checkUserId();
  },
  watch:{
  currentPage() {  
    this.calculateTableHeight()  
  },  
  pageSize() {  
    this.calculateTableHeight()  
  }
  },
  methods:{
    checkUserRole() {
      const token = localStorage.getItem('token'); // 从本地存储获取 token
      if (token) {
        const decodedToken = jwtDecode(token); // 解码 token
        return decodedToken.role === 'SUPERMAN'; // 检查角色
      }
      return false; // 无 token 返回 false
    },
    checkUserId() {
      const token = localStorage.getItem('token'); // 从本地存储获取 token
      if (token) {
        const decodedToken = jwtDecode(token); // 解码 token
        return decodedToken.userId; // 检查角色
      }
      return false; // 无 token 返回 false
    },
    canEditItem(row) {
  const isSuperman = this.checkUserRole();
  return isSuperman || (this.userId === row.userId && row.examine !== "审核通过");
},
    editItem(row) {
      console.log(row);
      console.log(this.userId);
    this.editVacation = { ...row }; // 将选中的假期数据赋值给编辑表单
    
    this.showEditModal = true; // 显示编辑弹窗
  },
  updateVacationById() {
    this.$refs.editVacationForm.validate((valid) => {
      if (valid) {
        if(this.editVacation.state === "紧急"){
          this.editVacation.state = "1";
        }else if(this.editVacation.state === "重要"){
          this.editVacation.state = "2";
        }else if(this.editVacation.state === "正常"){
          this.editVacation.state = "3";
        }
        this.editVacation.name = '',
        this.editVacation.reviewer = '',
        updateVacation(this.editVacation)
          .then(response => {
            this.$message.success('假期申请更新成功');
            this.showEditModal = false; // 关闭编辑弹窗
            this.logItem.mn = "updateVacationById";
            this.logItem.opn = "更新假期申请-请假列表";
            this.logItem.res = "true";
            addLog(this.logItem);
            window.location.reload(); // 刷新假期列表
          })
          .catch(error => {
            this.$message.error('内容未修改，假期申请更新失败');
            this.logItem.mn = "updateVacationById";
            this.logItem.opn = "更新假期申请-请假列表";
            this.logItem.res = "false";
            addLog(this.logItem);
            console.error(error);
          });
      } else {
        return false; // 表单验证失败的处理
      }
    });
  },
  closeEditModal() {
    this.showEditModal = false; // 关闭编辑弹窗
    this.editVacation = { // 重置编辑表单数据
      name: '',
      type: '',
      starttime: '',
      deadline: '',
      reason: '',
      state: '',
      reviewer: null,
      examine: '0'
    };
  },
    viewItem(row) {  
  // 将选中的假期申请信息赋值给 detailItem  
  getVacationDetailById(row.id).then((response)=>{
  this.showDetailModal = true; // 显示详情弹窗  
  this.detailItem = response.data;
  console.log(response.data);
  this.logItem.mn = "viewItem";
  this.logItem.opn = "查看假期申请详情-请假列表";
  this.logItem.res = "true";
  addLog(this.logItem);
  })
},  
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的请假信息-请假列表";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-请假列表";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
  calculateTableHeight() {  
    // 获取当前页展示的数据量  
    const currentPageData = this.filteredVacationData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
    
    // 每行高度为 50px，再加上表头高度 50px，得到总高度  
    let height = (currentPageData.length + 1) * 70
    // 限制高度在 minTableHeight 和 maxTableHeight 之间  
    this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight))  
  },
  filterData() {
    // 触发计算属性更新
  }
  } 
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
</style>